import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import {Form, Input, InputNumber, Radio, Modal, Select, Upload, message} from 'antd'
import {t, Trans} from "@lingui/macro"
import ImgCrop from "antd-img-crop";
import {LoadingOutlined, PlusOutlined} from "@ant-design/icons";
import api from '../../../services/api'
import store from "store";

const {createUserAvatar} = api
const { Option } = Select;
const FormItem = Form.Item

const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 14,
  },
}

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

function beforeUpload(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
}

class UserModal extends PureComponent {
  formRef = React.createRef()

  state = {
    value: [],
    loading: false, //上传 loading
  };

  //头像上传句柄
  handleChange = info => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      //设置表单值
      this.formRef.current.setFieldsValue({avatar: info.file.response.payload})
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imageUrl =>
        this.setState({
          imageUrl,
          loading: false,
        }),
      );
    }
  };

  handleOk = () => {
    const { item = {}, onOk,roleOptions } = this.props

    this.formRef.current.validateFields()
      .then(values => {
        const data = {
          ...values,
          key: item.key,
        }
        //fixed select value
        if(values.roleIds) {
          values.roleIds.forEach(function(v,i){
            roleOptions.forEach(function(vo){
              if(v == vo.name) {
                values.roleIds[i] = vo.id;
              }
            })
          })
        }
        onOk(data)
      })
      .catch(errorInfo => {
        console.log(errorInfo)
      })
  }

  render() {
    const { item = {}, onOk, form, roleOptions, ...modalProps } = this.props
    // delete item.password
    // delete item.roleIds
    //生成角色选项
    const children = [];
    const defaultRoleCheck = [];


    if(roleOptions) {
      roleOptions.forEach(function(v, k){
        children.push(<Option key={v.id}>{v.name}</Option>);
        //判断是否选中
        if(item.roleIds) {
          item.roleIds.forEach(function(roleId){
            if(v.id == roleId) {
              defaultRoleCheck.push(v.name)
            }
          })
        }

      })
    }


    let { loading, imageUrl } = this.state;
    //检查原值
    if(item.avatar != null && imageUrl == null) {
      imageUrl = item.avatar
    }
    let token = store.get('token')

    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );

    return (

      <Modal {...modalProps} onOk={this.handleOk}>
        <Form ref={this.formRef} name="control-ref" initialValues={{ ...item, roleIds:defaultRoleCheck,password:"" }} layout="horizontal">
          <FormItem name='username' rules={[{ required: true }]}
            label={t`Name`} hasFeedback {...formItemLayout}>
            <Input />
          </FormItem>
          <FormItem name='nickName' rules={[{ required: true }]}
            label={t`NickName`} hasFeedback {...formItemLayout}>
            <Input />
          </FormItem>
          <FormItem name='password' rules={[{ required: false }]}
            label={t`Password`} hasFeedback {...formItemLayout}>
            <Input.Password placeholder="input password" />
          </FormItem>

          <FormItem name='avatar' rules={[{ required: false }]}
            label={t`Avatar`} hasFeedback {...formItemLayout}>
            <ImgCrop rotate>

              <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action={createUserAvatar}
                beforeUpload={beforeUpload}
                onChange={this.handleChange}
                headers={{Authorization:token}}
              >
                {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
              </Upload>

            </ImgCrop>
          </FormItem>

          <FormItem name='sex' rules={[{ required: true }]}
            label={t`Gender`} hasFeedback {...formItemLayout}>
            <Radio.Group>
              <Radio value={1}>
                {t`Male`}
              </Radio>
              <Radio value={2}>
                {t`Female`}
              </Radio>
            </Radio.Group>
          </FormItem>
          <FormItem name='age' label={t`Age`} hasFeedback {...formItemLayout}>
            <InputNumber min={0} max={200} />
          </FormItem>
          <FormItem name='phone' rules={[{ required: true, pattern: /^1[34578]\d{9}$/, message: t`The input is not valid phone!`, }]}
            label={t`Phone`} hasFeedback {...formItemLayout}>
            <Input />
          </FormItem>
          <FormItem name='email' rules={[{ required: true, pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/, message: t`The input is not valid E-mail!`, }]}
            label={t`Email`} hasFeedback {...formItemLayout}>
            <Input />
          </FormItem>


          <FormItem name='roleIds' rules={[{required: false }]}
                    label={t`Select role`} hasFeedback {...formItemLayout}>
            <Select mode="multiple" value={item.roleIds} defaultValue={item.roleIds} placeholder={t`Select country`} style={{ width: '100%' }} >
              {children}
            </Select>
          </FormItem>
        </Form>
      </Modal>
    )
  }
}

UserModal.propTypes = {
  type: PropTypes.string,
  item: PropTypes.object,
  roleOptions: PropTypes.object,
  onOk: PropTypes.func,
}

export default UserModal
